package MyRemoteSorter;
import java.io.Serializable;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

public class QuickSort extends UnicastRemoteObject implements ISorter, Serializable
{
	Comparable[] workArray;
	public QuickSort()throws RemoteException
	{
		super();
	}

	public Comparable[] sort(Comparable[] inputArray)
	{
		if (inputArray == null)
			throw new IllegalArgumentException("De array is leeg.");
		else 
		{
			workArray = inputArray;
			quickSort(0, inputArray.length - 1 );
			return workArray;
		}
	}
	
	public void quickSort (int lowerIndex, int higherIndex)
	{
	    int li=lowerIndex, hi=higherIndex;
	    Comparable pivot=workArray[(lowerIndex+higherIndex)/2];
	    do
	    {    
	        while (workArray[li].compareTo(pivot)<0) li++; 
	        while (workArray[hi].compareTo(pivot)>0) hi--;
	        if (li<=hi)
	        {
	        	swapObject(li,hi);
	            li++; 
	            hi--;
	        }
	    }
	    while (li<=hi);
		if (lowerIndex<hi) quickSort(lowerIndex, hi);
		if (li<higherIndex) quickSort(li, higherIndex);
	}

	private void swapObject(int lowerIndex, int higherIndex) {
		Comparable tempObject=workArray[lowerIndex]; 
        workArray[lowerIndex]=workArray[higherIndex]; 
        workArray[higherIndex]=tempObject;
	}
}

    
    
    
